package com.grace.cms.general.listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.grace.cms.common.constant.CmsCacheConstant;
import com.grace.cms.common.enums.EventTypeEnums;
import com.grace.cms.common.enums.RecordTypeEnums;
import com.grace.cms.common.event.PublicPublishEvent;
import com.grace.cms.common.model.EventModel;
import com.grace.cms.common.service.IPublicPublishListener;
import com.grace.cms.general.cache.GeneralArticleCacheService;
import com.grace.redis.utils.RedisCache;

/**
 * 前台文章缓存刷新监听器
 */
@Component
public class PublicPublishListenerWeb implements IPublicPublishListener {
    
    @Autowired
    private RedisCache redisCache;

    @Override
    public void onApplicationEvent(PublicPublishEvent event) {
        
        // 获取事件模型
        EventModel eventModel = event.getEventModel();
        if (eventModel == null) {
            return;
        }
        // 只处理更新类型的事件
        if (EventTypeEnums.UPDATE.equals(eventModel.getEventType())) {
            handleCacheRefresh(eventModel);
        } else {

        }
    }

    /**
     * 处理缓存刷新事件
     * 
     * @param eventModel 事件模型
     */
    private void handleCacheRefresh(EventModel eventModel) {
        // 获取事件来源
        RecordTypeEnums eventFrom = eventModel.getEventFrom();
        // 获取事件ID
        String eventId = eventModel.getEventId();
        switch (eventFrom) {
            case ARTICLE:
                refreshCache(GeneralArticleCacheService.baseKeyPrefix, eventId);
                break;
            case CATEGORY:
                // 刷新分类缓存
                // 可以根据需要实现分类缓存刷新逻辑
                break;
            case COMMENT:
                refreshCache(CmsCacheConstant.getDataKeyPrefix(CmsCacheConstant.COMMENT_CACHE_KEY_PREFIX,
            CmsCacheConstant.CACHE_DATA, CmsCacheConstant.DATA_ALL), eventId);
                break;
            case THEME:
                // 刷新主题缓存
                // 可以根据需要实现主题缓存刷新逻辑
                break;
            case PAGE:
                // 刷新页面缓存
                // 可以根据需要实现页面缓存刷新逻辑
                break;
            default:
                // 其他类型的缓存刷新
                break;
        }
    }
    
    private void refreshCache(String cacheKeyPrefix, String cacheKey) {
        if (cacheKeyPrefix != null && !cacheKeyPrefix.isEmpty() && cacheKey != null && !cacheKey.isEmpty()) {
            try {
                redisCache.deleteCacheMapValue(cacheKeyPrefix, cacheKey);
            } catch (Exception e) {

            }
        }
    }
}
